#include "gameroom.h"
#include "ui_gameroom.h"

GameRoom::GameRoom(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GameRoom)
{
    ui->setupUi(this);
    this->setWindowIcon(QIcon(":/res/ico.png"));
    this->setWindowTitle("GreedySnake game");

    //painter=QPainter(this);

    //初始化贪吃蛇
    snakeList.push_back(QRectF(qrand()%1450,qrand()%this->height(),kSnakeNodeWeight,kSnakeNodeHeight));

    moveUp();

    createFood();

    timer=new QTimer(this);
    connect(timer,&QTimer::timeout,this,[=](){
        int cnt=1;
        if(snakeList.front().intersects(foodRect))
        {
            createFood();
            cnt++;
        }

        while(cnt--)
        {
            switch(moveDirect)
            {
            case SnakeDirect::UP:
                moveUp();
                break;
            case SnakeDirect::DOWN:
                moveDown();
                break;
            case SnakeDirect::LEFT:
                moveLeft();
                break;
            case SnakeDirect::RIGHT:
                moveRight();
                break;
            default:
               return -1;
                break;
            }

        }

        snakeList.pop_back();

        update();
    });
}

GameRoom::~GameRoom()
{
    delete ui;
}

void GameRoom::paintEvent(QPaintEvent *event)
{
    (void)event;
    QPainter painter(this);
    QPixmap pix_left(":/res/gameroom_left.png");
    QPixmap pix_right(":/res/gameroom_right.png");

    painter.drawPixmap(0,0,1500,this->height(),pix_left);
    painter.drawPixmap(1500,0,this->width(),this->height(),pix_right);


    QPixmap snake_pix;
    //绘制蛇头
    if(moveDirect==SnakeDirect::UP)
        snake_pix.load(":/res/snake_up.png");
    else if(moveDirect==SnakeDirect::DOWN)
        snake_pix.load(":/res/snake_down.png");
    else if(moveDirect==SnakeDirect::LEFT)
        snake_pix.load(":/res/snake_left.png");
    else if(moveDirect==SnakeDirect::RIGHT)
        snake_pix.load(":/res/snake_right.png");

    auto snakeHead=snakeList.front();
    painter.drawPixmap(snakeHead.x(),snakeHead.y(),snakeHead.width(),snakeHead.height(),snake_pix);

    //绘制蛇身
    snake_pix.load(":/res/body1.png");
    for(int i=1;i<snakeList.size()-1;i++)
    {
        auto node=snakeList.at(i);
        painter.drawPixmap(node.x(),node.y(),node.width(),node.height(),snake_pix);
    }

    //绘制蛇尾
    auto snakeTail=snakeList.back();
    painter.drawPixmap(snakeTail.x(),snakeTail.y(),snakeTail.width(),snakeTail.height(),snake_pix);

    //绘制食物
    QPixmap food_pix;
    for(int i=0;i<1;i++)
    {
        int foodId=qrand()%5;
        switch(foodId)
        {
            case SnakeFood::CAFE:
                food_pix.load(":/res/food_cafe.png");
                break;
            case SnakeFood::KORA:
                food_pix.load(":/res/food_kora.png");
                break;
            case SnakeFood::MUSHROOM:
                food_pix.load(":/res/food_mushroom.png");
                break;
            case SnakeFood::ORANGE:
                food_pix.load(":/res/food_orange.png");
                break;
            case SnakeFood::TOAST:
                food_pix.load(":/res/food_toast.png");
                break;
            default:
                food_pix.load(":/res/food_cafe.png");
                break;
        }
        int x=qrand()%1450;
        int y=qrand()%this->height();
        //painter.drawPixmap(x,y,foodRect.width(),foodRect.height(),food_pix);
        painter.drawPixmap(foodRect.x(),foodRect.y(),foodRect.width(),foodRect.height(),food_pix);
    }

    //绘制分数
    QPixmap pix_score(":/res/gameroom_score.png");
    painter.drawPixmap(1600,0,500,300,pix_score);

    QPen pen;
    pen.setColor(Qt::black);
    painter.setPen(pen);
    QFont font("黑体",25);
    painter.setFont(font);
    painter.drawText(1750,200,QString("%1").arg(snakeList.size()));

//    if(checkFail()==true)
//    {
//        QMessageBox *msg=new QMessageBox();
//        msg->setStyleSheet("QMessageBox {width: 600px; height: 400px;}");
//        msg->setText("DIE!!!!");
//        msg->setWindowTitle("DIE");
//        QPushButton *ok=new QPushButton("ok");
//        QString style="QPushButton{width:290px;height:90px;border-radius:10px;background-color:rgb(106, 121, 255);color:rgb(0, 0, 0);font-size:50px;}"
//                      "QPushButton:hover{background-color:skyblue;}";
//        ok->setStyleSheet(style);
//        msg->addButton(ok,QMessageBox::AcceptRole);
//        int ret=msg->exec();
//        if(ret==QMessageBox::AcceptRole)
//            msg->close();
//        qDebug()<<"die";
//        this->close();
//        GameSelect *gameselect=new GameSelect;
//        gameselect->show();
//        painter.end();
//        timer->stop();
//        gameOver();
//        painter.end();
//    }
//    painter.end();
}

void GameRoom::on_up_clicked()
{
    //if(moveDirect!=SnakeDirect::DOWN)
        moveDirect=SnakeDirect::UP;
}

void GameRoom::on_down_clicked()
{
    //if(moveDirect!=SnakeDirect::UP)
        moveDirect=SnakeDirect::DOWN;
}

void GameRoom::on_left_clicked()
{
    //if(moveDirect!=SnakeDirect::RIGHT)
        moveDirect=SnakeDirect::LEFT;
}

void GameRoom::on_right_clicked()
{
    //if(moveDirect!=SnakeDirect::LEFT)
        moveDirect=SnakeDirect::RIGHT;
}

void GameRoom::on_exit_clicked()
{
    QMessageBox *msg=new QMessageBox(this);
    msg->setStyleSheet("QMessageBox {width: 800px; height: 600px;}");
    msg->setText("Are you sure to exit the game?");
    msg->setWindowTitle("exit game");
    QPushButton *ok=new QPushButton("ok");
    QPushButton *cancel=new QPushButton("cancel");
    QString style="QPushButton{width:290px;height:90px;border-radius:10px;background-color:rgb(106, 121, 255);color:rgb(0, 0, 0);font-size:50px;}"
                  "QPushButton:hover{background-color:skyblue;}";
    ok->setStyleSheet(style);
    cancel->setStyleSheet(style);
    msg->addButton(ok,QMessageBox::AcceptRole);
    msg->addButton(cancel,QMessageBox::RejectRole);
    int ret=msg->exec();
    if(ret==QMessageBox::AcceptRole)
    {
        this->close();
        GameSelect *gameselect=new GameSelect;
        gameselect->show();
        //qDebug()<<1;
    }
    else if(ret==QMessageBox::QMessageBox::RejectRole)
    {
        msg->close();
        //qDebug()<<2;
    }

}

bool GameRoom::checkFail()
{
    for(int i=0;i<snakeList.size();i++)
    {
        for(int j=i+1;j<snakeList.size();j++)
        {
            if(snakeList.at(i)==snakeList.at(j))
                return true;
        }
    }
    return false;
}

void GameRoom::moveUp()
{
    if(isover==false&&checkFail()==true)
    {
        //qDebug()<<"up";
        isover=true;
        gameOver();
    }
    moveDirect=SnakeDirect::UP;
    QPointF leftTop;   //蛇节点左上角
    QPointF  rightBottom;  //蛇节点右下角

    auto snakeTop=snakeList.front();  //获取贪吃蛇链表的头节点

    int headX=snakeTop.x();
    int headY=snakeTop.y();

    if(headY<0)  //越界了(穿墙了)
    {
        //gameOver();
        leftTop=QPointF(headX,this->height()-kSnakeNodeHeight);
    }
    else
        leftTop=QPointF(headX,headY-kSnakeNodeHeight);

    rightBottom=QPointF(leftTop.x()+kSnakeNodeWeight,leftTop.y()+kSnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveDown()
{
    if(isover==false&&checkFail()==true)
    {
        //qDebug()<<"Down";
        isover=true;
        gameOver();
    }
    moveDirect=SnakeDirect::DOWN;
    QPointF leftTop;   //蛇节点左上角
    QPointF  rightBottom;  //蛇节点右下角

    auto snakeTop=snakeList.front();  //获取贪吃蛇链表的头节点

    int headX=snakeTop.x();
    int headY=snakeTop.y();

    if(headY>this->height())
    {
        //gameOver();
        leftTop=QPointF(headX,0);
    }
    else
        leftTop=snakeTop.bottomLeft();

   rightBottom=QPointF(leftTop.x()+kSnakeNodeWeight,leftTop.y()+kSnakeNodeHeight);
   snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveLeft()
{
    if(isover==false&&checkFail()==true)
    {
        //qDebug()<<"left";
        isover=true;
        gameOver();
    }
    moveDirect=SnakeDirect::LEFT;
    QPointF leftTop;   //蛇节点左上角
    QPointF  rightBottom;  //蛇节点右下角

    auto snakeTop=snakeList.front();  //获取贪吃蛇链表的头节点

    int headX=snakeTop.x();
    int headY=snakeTop.y();

    if(headX<0)
    {
        //gameOver();
        leftTop=QPointF(1500-kSnakeNodeWeight,headY);
    }
    else
        leftTop=QPointF(headX-kSnakeNodeWeight,headY);

    rightBottom=QPointF(leftTop.x()+kSnakeNodeWeight,leftTop.y()+kSnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveRight()
{

    if(isover==false&&checkFail()==true)
    {
        //qDebug()<<"right";
        isover=true;
        gameOver();
    }
    moveDirect=SnakeDirect::RIGHT;
    QPointF leftTop;   //蛇节点左上角
    QPointF  rightBottom;  //蛇节点右下角

    auto snakeTop=snakeList.front();  //获取贪吃蛇链表的头节点

    int headX=snakeTop.x();
    int headY=snakeTop.y();

    if(headX>1500)
    {
        //gameOver();
        leftTop=QPointF(0,headY);
    }
    else
        leftTop=snakeTop.topRight();

    rightBottom=QPointF(leftTop.x()+kSnakeNodeWeight,leftTop.y()+kSnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::createFood()
{
    foodRect=QRectF(qrand()%(1500/kSnakeNodeWeight)*kSnakeNodeHeight,
                    qrand()%(this->height()/kSnakeNodeWeight)*kSnakeNodeHeight,
                    kSnakeNodeWeight,kSnakeNodeHeight);
}

void GameRoom::on_start_clicked()
{
    isGameStart=true;
    timer->start(DefaultSpeed);
}

void GameRoom::on_stop_clicked()
{

    isGameStart=false;
    timer->stop();
}

void GameRoom::gameOver()
{  
    isover=true;
    QMessageBox *msg=new QMessageBox();
    msg->setStyleSheet("QMessageBox {width: 600px; height: 400px;}");
    msg->setText("GAMEOVER!!!");
    msg->setWindowTitle("gameover");
    msg->setWindowIcon(QIcon(":/res/ico.png"));
    QPushButton *ok=new QPushButton("ok");
    QString style="QPushButton{width:290px;height:90px;border-radius:10px;background-color:rgb(106, 121, 255);color:rgb(0, 0, 0);font-size:50px;}"
                  "QPushButton:hover{background-color:skyblue;}";
    ok->setStyleSheet(style);
    msg->addButton(ok,QMessageBox::AcceptRole);
    int ret=msg->exec();
    if(ret==QMessageBox::AcceptRole)
    {
        msg->close();
        QFile file("D:/GreedySnake/Snake/his_score.txt");
        file.open(QIODevice::Append | QIODevice::Text);
        if(file.isOpen()==false)
            exit(-1);
        QDateTime currentTime=QDateTime::currentDateTime();
        QString modeString;
        switch (mode)
        {
            case SIMPLE:
                modeString="SIMPLE";
                break;
            case NORMAL:
                modeString="NORMAL";
                break;
            case HARD:
                modeString="HARD";
                break;
            default:
                modeString="MODE ERROR";
                break;
        }
        QString score="["+currentTime.toString("yyyy-MM-dd hh:mm:ss")+"]"+modeString+" " +QString::number(snakeList.size())+"\n";
        file.write(score.toUtf8());
        file.close();
        this->close();
        GameSelect *gameselect=new GameSelect;
        gameselect->show();
    }
}

void GameRoom::SetMode(int speed)
{
    DefaultSpeed=speed;
    mode=speed;
}
